<template>
	<view class="page-main">
		<view class="recent-anniversary" @longpress="onEdit(null,0,false)">
			<view class="birthday">
				<view>
					我的生日还有
				</view>
				<view style="margin-bottom: 26rpx;">
					<text class="birthday-days">
						<text v-if="userBirthday">{{Math.ceil((userBirthday - newDate) / oneDay)}}</text>
						<text v-else>请先完善生日信息</text>
					</text>
					<text style="font-size: 14px;">天</text>
				</view>
				<view class="birthday-date">
					<text>目标日：</text>
					<text>{{$u.timeFormat(userBirthday, 'yyyy年mm月dd日')}}</text>
				</view>
			</view>
			<view class="right">
				<image class="birthday-cakes" src="/static/birthday-cakes.png" />
			</view>
		</view>
		<view class="record-list" v-if="partnerBirthday" @longpress="onEdit(null,1,false)">
			<view class="record-list-desc">
				<image class="record-list-icon" src="/static/birthday_icon.png" />
				<text>{{vuex_user.sex===1?"她":"他"}}的生日还有</text>
			</view>
			<view class="right" style="color: #646464;">
				<text v-if="partnerBirthday">{{Math.ceil((partnerBirthday - newDate) / oneDay)}}天</text>
				<text v-else>对方为完善生日信息</text>
			</view>
		</view>
		<view class="record-list" v-if="loveTime" @longpress="onEdit(null,2,false)">
			<view class="record-list-desc">
				<image class="record-list-icon" src="/static/cupid.png" />
				<text>我们在一起已有</text>
			</view>
			<view class="right" style="color: #646464;">
				{{Math.ceil((newDate - loveTime) / oneDay)}}天
			</view>
		</view>
		<view class="record-list" v-for="(item,index) in list" :key="index" @longpress="onEdit(item,index,true)">
			<view class="record-list-desc">
				<image class="record-list-icon" src="/static/heart.png" />
				<text>{{item.content + (newDate.getTime() > item.date ? '已有' : '还有')}}</text>
			</view>
			<view class="right" style="color: #646464;">
				{{Math.ceil(Math.abs(newDate - item.date) / oneDay)}}天
			</view>
		</view>

		<u-loadmore v-if="isLoadmore" status="loading" height="60rpx" />

		<fixed-button @click="onAdd()" />

		<u-action-sheet :actions="actionSheet" :show="showActionSheet" cancelText="取消" @close="showActionSheet=false"
			@select="onActionSelect" closeOnClickOverlay safeAreaInsetBottom />

		<u-modal :show="showModal" title="纪念日" showCancelButton @cancel="modalCancel" @confirm="modalConfirm">
			<u--form ref="uForm" labelPosition="left" labelWidth="auto" :model="modelForm" :rules="rules">
				<u-form-item label="内容" prop="content" borderBottom required>
					<u--input v-model="modelForm.content" :disabled="!isList" disabledColor="#ffffff"
						placeholder="请输入内容" border="none" inputAlign="right" />
				</u-form-item>
				<u-form-item label="日期" prop="date" borderBottom required @click="showDatetimePicker=true">
					<u--input v-model="modelForm.date" disabled disabledColor="#ffffff" placeholder="请选择日期"
						border="none" inputAlign="right" />
					<u-icon slot="right" name="arrow-right" />
				</u-form-item>
			</u--form>
		</u-modal>

		<u-datetime-picker ref="datetimePicker" :show="showDatetimePicker" :value="newDate" :formatter="formatter"
			title="选择日期" mode="date" closeOnClickOverlay :minDate="new Date('1970-1-1').getTime()"
			@close="showDatetimePicker=false" @cancel="showDatetimePicker=false" @confirm="pickerConfirm" />
	</view>
</template>

<script>
	import fixedButton from '@/components/myCustom/fixed-button'

	export default {
		components: {
			fixedButton
		},
		data() {
			return {
				newDate: new Date(),
				oneDay: 1000 * 60 * 60 * 24,
				userBirthday: null,
				partnerBirthday: null,
				loveTime: this.$tools.getPartnerConfig() ? this.$tools.getPartnerConfig().partnerTime : null,
				currentPage: 1, //当前页数
				pageSize: 10, //每页数据条数
				totalData: 1, //数据总数
				tmpInsert: 0, //零时插入的数据条数
				list: [],
				modelForm: {
					id: null,
					content: '',
					date: ''
				},
				isList: true,
				showModal: false,
				isLoadmore: false,
				showDatetimePicker: false,
				rules: {
					content: {
						type: 'string',
						required: true,
						message: '请输入内容',
						trigger: ['blur', 'change']
					},
					formatDate: {
						type: 'string',
						required: true,
						message: '请选择日期',
						trigger: ['blur', 'change']
					},
				},
				showActionSheet: false,
				actionSheet: [{
					name: '修改',
					value: 0
				}, {
					name: '删除',
					value: 1,
					disabled: false
				}, ],
			}
		},
		onLoad() {
			this.newDate.setHours(0)
			this.newDate.setMinutes(0)
			this.newDate.setSeconds(0)
			this.newDate.setMilliseconds(0)

			const newYear = this.newDate.getFullYear()
			const birthYear = new Date(this.vuex_user.birthYear)
			this.userBirthday = new Date(newYear, birthYear.getMonth(), birthYear.getDate())

			if (this.userBirthday < this.newDate) {
				this.userBirthday.setFullYear(newYear + 1);
			}

			const partner = this.$tools.getPartner()
			if (partner && partner.birthYear) {
				this.partnerBirthday = new Date(partner.birthYear)
				this.partnerBirthday = new Date(newYear, this.partnerBirthday.getMonth(), this.partnerBirthday.getDate())
				if (this.partnerBirthday < this.newDate) {
					this.partnerBirthday.setFullYear(newYear + 1);
				}
			}

			this.onList()
		},
		onReady() {
			this.$refs.datetimePicker.setFormatter(this.formatter)
		},
		onReachBottom() {
			this.onList()
		},
		methods: {
			onList() {
				if (this.totalData > this.list.length) {
					this.isLoadmore = true
					this.$http.get("/anniversaries/page", {
						page: this.currentPage,
						size: this.pageSize,
						partnerConfigId: this.vuex_user.configId || ''
					}).then((res) => {
						let data = res.data
						this.list.push(...data.records)
						this.isLoadmore = false
						this.totalData = data.total
						this.currentPage += 1
						this.tmpInsert = 0
					}).catch((err) => {
						this.isLoadmore = false
					})
				}
			},
			onAdd() {
				this.modelForm.id = null
				this.modelForm.content = null
				this.modelForm.date = null
				this.isList = true
				this.showModal = true
			},
			onActionSelect(e) {
				this.showActionSheet = false
				if (e.value === 0) { //选中修改
					this.showModal = true
				} else if (e.value === 1) { //选中删除
					uni.showModal({
						title: "提示",
						content: `确定要删除 “${this.modelForm.content}” 吗？`,
						success: (res) => {
							if (res.confirm) {
								uni.showLoading({
									title: '删除中',
									mask: true
								});
								this.$http.post("/anniversaries/delete", {
									id: this.modelForm.id
								}).then((res) => {
									this.list.splice(this.modelForm.listIndex, 1)
									uni.hideLoading();
									uni.$u.toast('删除成功');
								}).catch((err) => {
									uni.hideLoading();
									uni.$u.toast(err.message);
								})

							}
						}
					});
				}
			},
			onEdit(item, index, isList) {
				const form = this.modelForm
				if (isList) { //是否是查询的列表
					form.id = item.id
					form.content = item.content
					form.date = item.date
					this.actionSheet[1].disabled = false
				} else if (index === 2) {
					form.content = '我们在一起'
					form.date = this.loveTime
					this.actionSheet[1].disabled = true
				} else if (index === 0) {
					const distance = Math.ceil((this.userBirthday - this.newDate) / this.oneDay),
						formatDate = uni.$u.timeFormat(this.userBirthday, 'yyyy年mm月dd日')
					uni.showModal({
						title: '我的生日',
						content: `下次生日：${formatDate} \n 距离下次生日还有：${distance}天`,
						showCancel: false
					});
					return
				} else if (index === 1) {
					const distance = Math.ceil((this.partnerBirthday - this.newDate) / this.oneDay),
						formatDate = uni.$u.timeFormat(this.partnerBirthday, 'yyyy年mm月dd日')
					uni.showModal({
						title: 'Ta的生日',
						content: `${this.$tools.getPartner().nickName}的下次生日：${formatDate} \n 距离下次生日还有：${distance}天`,
						showCancel: false
					});
					return
				}

				this.showActionSheet = true
				form.listIndex = index
				this.isList = isList
				this.$refs.datetimePicker.updateColumnValue(form.date)
			},
			modalCancel() {
				this.showModal = false;
				this.showDatetimePicker = false;
				this.$refs.uForm.clearValidate()
			},
			modalConfirm() {
				if (vuex_user.state == 0) {
					uni.$u.toast('请先绑定伴侣')
					return
				}
				this.$refs.uForm.validate().then(res => {
					this.showModal = false;
					this.showDatetimePicker = false;
					uni.showLoading({
						title: '操作中',
						mask: true
					});
					const db = uniCloud.database(),
						form = this.modelForm
					if (this.isList) {
						//修改列表内容
						if (form.id) {
							this.$http.post("/anniversaries/update", {
								id: form.id,
								content: form.content,
								date: form.date
							}).then((res) => {
								const item = this.list[form.listIndex]
								item.content = form.content
								item.date = form.date
								uni.hideLoading();
								uni.$u.toast('修改成功')
							}).catch(err => {
								uni.hideLoading();
								uni.$u.toast(err.message)
							})
							return
						}
						//添加列表内容
						const addForm = {
							partnerConfigId: this.vuex_user.configId,
							content: form.content,
							date: form.date,
						}
						this.$http.post("/anniversaries/add", addForm)
							.then((res) => {
								addForm.id = res.data.id
								this.list.unshift(addForm)
								this.tmpInsert += 1
								this.totalData += 1
								uni.hideLoading();
								uni.$u.toast('添加成功')
							}).catch(err => {
								uni.hideLoading();
								uni.$u.toast(err.message)
							})
						return
					}
					//修改非列表内容
					this.$http.post("/partnerConfig/update", {
						id: this.vuex_user.configId,
						partnerTime: form.date
					}).then((res) => {
						this.loveTime = form.date
						this.$tools.setPartnerConfig({
							partnerTime: form.date
						})
						uni.hideLoading();
						uni.$u.toast('修改成功')
					}).catch(err => {
						uni.hideLoading();
						uni.$u.toast(err.message)
					})
				})
			},
			pickerConfirm(e) {
				this.modelForm.date = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
				this.showDatetimePicker = false
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				} else if (type === 'month') {
					return `${value}月`
				} else if (type === 'day') {
					return `${value}日`
				}
				return value
			},
		}
	}
</script>

<style>
	page {
		--bg-image: none;
		background-color: #f00;
	}

	.page-main {
		padding: 30rpx;
	}

	.recent-anniversary {
		position: relative;
		margin-bottom: 30rpx;
		background-color: #fff;
		border-radius: 10px;

	}

	.birthday {
		padding: 20px 0 20px 20px;
		display: inline-block;
		width: 400rpx;
		overflow: hidden;
	}

	.birthday-days {
		font-size: 80rpx;
		color: #ff301e;
	}

	.birthday-date {
		color: #a0a0a0;
	}

	.birthday-cakes {
		width: 240rpx;
		height: 240rpx;
		position: absolute;
		bottom: 0;
		right: 0;
	}

	.record-list {
		padding: 36rpx;
		margin-bottom: 30rpx;
		background-color: #fff;
		border-radius: 10px;
	}

	.record-list-desc {
		display: inline-block;
		width: 460rpx;
	}

	.record-list-icon {
		width: 21px;
		height: 21px;
		float: left;
		margin-right: 10px;
	}

	.left {
		float: left;
	}

	.right {
		float: right;
	}

	.area {
		width: 100%;
		height: 400rpx;
		background-color: yellow;
	}

	.view {
		width: 140rpx;
		height: 40rpx;
		background-color: red;
	}
</style>